package com.cc8w.security;


import java.util.ArrayList;
import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cc8w.entity.UserEntity;
import com.cc8w.home.service.UserService;

/** 
 * 一个自定义的service用来和数据库进行操作. 即以后我们要通过数据库保存权限.则需要我们继承UserDetailsService 
 *  
 */  
@Service
public class CustomUserDetailsService implements UserDetailsService {  
    protected static Logger logger = Logger.getLogger("service");

	@Autowired
	public UserService userService;
    
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		
		try {
	        UserEntity userPojo = userService.queryUserByUserName(username);
	        System.out.println(userPojo);
	        if(userPojo==null) return null;
	        //List<? extends GrantedAuthority> role = new ArrayList<SimpleGrantedAuthority>();
	        List<SimpleGrantedAuthority> role = new ArrayList<>();
	        
	        role.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//一般循环加入角色
	        role.add(new SimpleGrantedAuthority("ROLE_USER"));//一般循环加入角色
	   
	        //${noop}后面是明文密码,就是密码不加密
	        //UserDetails user = new User(userPojo.getUserName(), "{noop}"+userPojo.getPassWord(), role) ;
	        //密码固定123456：$2a$10$Bz9kjIa/FwFgoEql.5iy5uU8X.KuQbIo3zF216Cmu1WzbpH.X3Pbq
	        //UserDetails user = new User(userPojo.getUserName(), userPojo.getPassWord(), role) ;
	        UserDetails user = new User(userPojo.getUserName(), "$2a$10$Bz9kjIa/FwFgoEql.5iy5uU8X.KuQbIo3zF216Cmu1WzbpH.X3Pbq", role) ;
	        
	        
	        return user;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("用户验证错误");
			return null;
		}

        

	}

    
} 
